﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Develop.DTO.DevelopProjectDevelopment;
using AnQinFrameWorkAPI.Entity.Develop.View.DevelopProjectDevelopment;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.JWT;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;
using static AnQinFrameWorkAPI.Common.Enum.DevelopEnum;

namespace AnQinFrameWorkAPI.Service.Develop;

/// <summary>
///     开发管理-项目开发业务层
/// </summary>
public class DevelopProjectDevelopmentService
{
    //数据库
    private readonly DatabaseContext _context;

    //自动映射
    private readonly IMapper _mapper;

    //请求人信息
    private readonly IUserContext _userContext;

    //构造注入
    public DevelopProjectDevelopmentService(IUserContext userContext, DatabaseContext context, IMapper mapper)
    {
        _userContext = userContext;
        _context = context;
        _mapper = mapper;
    }

    #region 获取开发管理项目开发列表

    public async Task<RequestResponseModel> GetProjectDevelopment(
        DevelopProjectDevelopmentSearchDTO developProjectDevelopmentSearchDTO)
    {
        //获取筛选
        var query = _context.DevelopProjectManager
            .ProjectTo<DevelopProjectDevelopmentView>(_mapper.ConfigurationProvider)
            .AsQueryable().Where(a => a.SaleStatus == SaleStatusEnum.已下定 || a.SaleStatus == SaleStatusEnum.已完成)
            .WhereIF(
                a => a.ProjectCode.Contains(developProjectDevelopmentSearchDTO.Project) ||
                     a.ProjectName.Contains(developProjectDevelopmentSearchDTO.Project),
                !string.IsNullOrEmpty(developProjectDevelopmentSearchDTO.Project))
            .WhereIF(a => a.DevelopStatus == developProjectDevelopmentSearchDTO.DevelopStatus,
                developProjectDevelopmentSearchDTO.DevelopStatus != null)
            .WhereIF(a => a.CreateTime > developProjectDevelopmentSearchDTO.StartTime,
                developProjectDevelopmentSearchDTO.StartTime != null)
            .WhereIF(a => a.CreateTime < developProjectDevelopmentSearchDTO.EndTime,
                developProjectDevelopmentSearchDTO.EndTime != null)
            .Where(a => a.IsDelete == false);

        //返回列表
        var developProjectDevelopment = await query
            .OrderBy(a => a.CreateTime)
            .Page(developProjectDevelopmentSearchDTO.PageIndex, developProjectDevelopmentSearchDTO.PageSize)
            .ToListAsync();

        //总数据量
        var pageCount = await query.CountAsync();

        //返回数据
        var pageResult = new PageResult<DevelopProjectDevelopmentView>(developProjectDevelopment, pageCount);
        return RequestResponse.OK(pageResult, "查询成功");
    }

    #endregion

    #region 开发管理项目开发 - 确认需求

    public async Task<RequestResponseModel> ConfirmArrayDevelopProjectDevelopment(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.DevelopProjectManager
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("项目Id无效");

        if (query.All(a => a.DevelopStatus != DevelopStatusEnum.待确认))
            return RequestResponse.BadRequest("只有状态为[待确认]的项目开发单才可以确认需求");

        foreach (var item in query) item.DevelopStatus = DevelopStatusEnum.待开发;

        //更新并保存
        _context.DevelopProjectManager.UpdateRange(query);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "确认成功");
    }

    #endregion

    #region 开发管理项目开发 - 开始开发

    public async Task<RequestResponseModel> StartDevelopProjectDevelopment(SingleIdDTO singleIdDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectManager, singleIdDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");
        ;

        if (query.DevelopStatus != DevelopStatusEnum.待开发) return RequestResponse.BadRequest("只有状态为[待开发]的项目开发单才可以开始开发");

        query.DevelopStatus = DevelopStatusEnum.开发中;

        //更新操作
        _context.DevelopProjectManager.Update(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(singleIdDTO.Id, "开始开发成功");
    }

    #endregion

    #region 开发管理项目开发 - 开发完成

    public async Task<RequestResponseModel> FinishDevelopProjectDevelopment(SingleIdDTO singleIdDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectManager, singleIdDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");
        ;

        if (query.DevelopStatus != DevelopStatusEnum.开发中) return RequestResponse.BadRequest("只有状态为[开发中]的项目开发单才可以开发完成");

        query.DevelopStatus = DevelopStatusEnum.已完成;
        query.ImplementStatus = ImplementStatusEnum.待实施;

        //更新操作
        _context.DevelopProjectManager.Update(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(singleIdDTO.Id, "开发完成成功");
    }

    #endregion

    #region 开发管理项目开发 - 取消

    public async Task<RequestResponseModel> CancelArrayDevelopProjectDevelopment(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.DevelopProjectManager
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("项目Id无效");

        if (query.Any(a => a.DevelopStatus == DevelopStatusEnum.已完成 || a.DevelopStatus == DevelopStatusEnum.已取消))
            return RequestResponse.BadRequest("已完成或者已取消的项目不能取消");

        foreach (var item in query) item.DevelopStatus = DevelopStatusEnum.已取消;
        ;

        //更新并保存
        _context.DevelopProjectManager.UpdateRange(query);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "项目取消成功");
    }

    #endregion

    #region 获取开发管理项目需求开发列表

    public async Task<RequestResponseModel> GetProjectDevelopmentDemand(
        DevelopProjectDemandDevelopmentSearchDTO developProjectDemandDevelopmentSearch)
    {
        //获取筛选
        var query = _context.DevelopProjectDemand
            .ProjectTo<DevelopProjectDemandDevelopmentView>(_mapper.ConfigurationProvider)
            .AsNoTracking().Where(a => a.ProjectId == developProjectDemandDevelopmentSearch.ProjectId)
            .WhereIF(
                a => a.Code.Contains(developProjectDemandDevelopmentSearch.Demand) ||
                     a.Name.Contains(developProjectDemandDevelopmentSearch.Demand),
                !string.IsNullOrEmpty(developProjectDemandDevelopmentSearch.Demand))
            .WhereIF(
                a => a.ProjectCode.Contains(developProjectDemandDevelopmentSearch.Project) ||
                     a.ProjectName.Contains(developProjectDemandDevelopmentSearch.Project),
                !string.IsNullOrEmpty(developProjectDemandDevelopmentSearch.Project))
            .WhereIF(a => a.Content.Contains(developProjectDemandDevelopmentSearch.Content),
                !string.IsNullOrEmpty(developProjectDemandDevelopmentSearch.Content))
            .WhereIF(a => a.DevelopStaffName.Contains(developProjectDemandDevelopmentSearch.DevelopStaffName),
                !string.IsNullOrEmpty(developProjectDemandDevelopmentSearch.DevelopStaffName))
            .WhereIF(a => a.DevelopItemStatus == developProjectDemandDevelopmentSearch.DevelopItemStatus,
                developProjectDemandDevelopmentSearch.DevelopItemStatus != null)
            .Where(a => a.IsDelete == false);

        //返回列表
        var developProjectDevelopmentDemand = await query
            .OrderBy(a => a.CreateTime)
            .Page(developProjectDemandDevelopmentSearch.PageIndex, developProjectDemandDevelopmentSearch.PageSize)
            .ToListAsync();

        //总数据量
        var pageCount = await query.CountAsync();

        //返回数据
        var pageResult =
            new PageResult<DevelopProjectDemandDevelopmentView>(developProjectDevelopmentDemand, pageCount);
        return RequestResponse.OK(pageResult, "查询成功");
    }

    #endregion

    #region 开发管理项目需求开发 - 确认需求

    public async Task<RequestResponseModel> ConfirmArrayDevelopProjectDemandDevelopment(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.DevelopProjectDemand
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("项目Id无效");

        if (query.All(a => a.DevelopItemStatus != DevelopItemStatusEnum.待确认))
            return RequestResponse.BadRequest("只有状态为[待确认]的项目开发需求单才可以确认需求");

        foreach (var item in query) item.DevelopItemStatus = DevelopItemStatusEnum.待开发;
        ;

        //更新并保存
        _context.DevelopProjectDemand.UpdateRange(query);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "确认成功");
    }

    #endregion

    #region 开发管理项目需求开发 - 开始开发

    public async Task<RequestResponseModel> StartDevelopProjectDemandDevelopment(SingleIdDTO singleIdDTO)
    {
        //校验开发人
        var staff = await Valid.ValidId(_context.Staff, _userContext.UserId);
        if (staff == null) return RequestResponse.BadRequest("员工不存在");

        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectDemand, singleIdDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");
        ;

        if (query.DevelopItemStatus != DevelopItemStatusEnum.待开发)
            return RequestResponse.BadRequest("只有状态为[待开发]的项目开发单才可以开始开发");

        query.DevelopItemStatus = DevelopItemStatusEnum.开发中;
        query.DevelopStartTime = DateTime.Now;
        query.DevelopStaffId = staff.Id.ToString();
        query.DevelopStaffName = staff.Name;

        //更新操作
        _context.DevelopProjectDemand.Update(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(singleIdDTO.Id, "开始开发成功");
    }

    #endregion

    #region 开发管理项目需求开发 - 开发完成

    public async Task<RequestResponseModel> FinishDevelopProjectDemandDevelopment(SingleIdDTO singleIdDTO)
    {
        //校验数据
        var query = await Valid.ValidId(_context.DevelopProjectDemand, singleIdDTO.Id);
        if (query == null) return RequestResponse.ErrorRequest("项目Id无效");
        ;

        if (query.DevelopItemStatus != DevelopItemStatusEnum.开发中)
            return RequestResponse.BadRequest("只有状态为[开发中]的项目开发单才可以开发完成");

        query.DevelopItemStatus = DevelopItemStatusEnum.已完成;
        query.DevelopEndTime = DateTime.Now;

        //更新操作
        _context.DevelopProjectDemand.Update(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(singleIdDTO.Id, "开始开发成功");
    }

    #endregion

    #region 开发管理项目需求开发 - 取消

    public async Task<RequestResponseModel> CancelArrayDevelopProjectDemandDevelopment(IdArrayDTO idArrayDTO)
    {
        //校验单据
        var query = await _context.DevelopProjectDemand
            .WhereIF(a => idArrayDTO.Ids.Contains(a.Id.ToString()), idArrayDTO != null)
            .ToListAsync();

        if (query.Count != idArrayDTO.Ids.Count) return RequestResponse.ErrorRequest("项目Id无效");

        if (query.Any(a =>
                a.DevelopItemStatus == DevelopItemStatusEnum.已完成 || a.DevelopItemStatus == DevelopItemStatusEnum.已取消))
            return RequestResponse.BadRequest("已完成或者已取消的项目需求不能取消");

        foreach (var item in query) item.DevelopItemStatus = DevelopItemStatusEnum.已取消;
        ;

        //更新并保存
        _context.DevelopProjectDemand.UpdateRange(query);
        await _context.SaveChangesAsync();
        return RequestResponse.OK(idArrayDTO.Ids, "项目需求取消成功");
    }

    #endregion
}